package com.stateflow.engine.util;

import com.stateflow.facade.common.util.CommonAssert;
import com.stateflow.facade.common.util.CommonUtils;
import com.stateflow.facade.common.util.StringUtils;
import com.stateflow.engine.config.KeySecretConfig;
import com.stateflow.engine.core.cache.UserAllDataCache;
import com.stateflow.engine.user.biz.dto.cache.UserAllDataCacheDTO;
import com.stateflow.engine.user.biz.dto.req.SignReqDTO;
import com.stateflow.facade.dto.req.SignRequestDTO;

/**
 * Created by weiqingming on 2019/11/29.
 * 校验sign
 */
public class SignCheckUtils {


    /**
     * 校验内部系统请求
     *
     * @param req
     * @param salts
     * @return
     */
    public static void checkInteriorSign(SignReqDTO req, String... salts) {
        String secret = KeySecretConfig.KEY_SECRET_MAP.get(req.getApply());
        CommonAssert.isNoBlankStr(secret, "无效的accesskey");

        String salt = StringUtils.compose(salts);
        String sign = CommonUtils.md5(req.getApply() + secret + salt);
        CommonAssert.isTrue(StringUtils.equals(sign, req.getSign()), "无效请求");
    }


    /**
     * 校验外部用户系统请求
     *
     * @param req
     * @param salts
     * @return
     */
    public static void checkUserSign(SignRequestDTO req, String... salts) {
        UserAllDataCacheDTO data = UserAllDataCache.get(req.getAccessKey());
        CommonAssert.isNoEmptyObj(data, "未查询到用户信息");

        String salt = StringUtils.compose(salts);
        String sign = CommonUtils.md5(req.getAccessKey() + data.getAccessSecret() + salt);
        CommonAssert.isTrue(StringUtils.equals(sign, req.getSign()), "无效请求");
    }
}
